<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会员中心-账号管理</title>
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome 图标 -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 自定义 Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1677ff', // 主色调，类似截图中的蓝色
                        lightBg: '#f5f7fa', // 浅背景色
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>
    <!-- 自定义工具类 -->
    <style>
        .content-auto {
            content-visibility: auto;
        }

        .sidebar-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            cursor: pointer;
            transition: all 200ms;
        }

        .sidebar-item.active {
            background-color: #3b82f6;
            color: white;
        }

        .sidebar-item:hover {
            background-color: #F3F4F6;
            color: #1F2937;
        }

        .login-button {
            width: 100%;
            padding: 0.75rem;
            border-radius: 0.5rem;
            background-color: #3b82f6;
            color: white;
            font-weight: 500;
            transition: all 200ms;
        }

        .login-button:hover {
            background-color: rgba(59, 130, 246, 0.9);
        }

        .account-card {
            transition: all 0.3s ease;
        }

        .account-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
    </style>
</head>

<body class="bg-lightBg min-h-screen flex">
    <!-- 登录弹窗 HTML -->
    <div id="loginModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
        <div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-gray-800">用户登录</h2>
                <button id="closeLoginModalBtn" class="text-gray-500 hover:text-gray-700 focus:outline-none">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <form id="loginForm" class="space-y-4">
                <div>
                    <label for="loginUsername" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" id="loginUsername" name="username"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="请输入用户名" required>
                </div>
                <div>
                    <label for="loginPassword" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
                    <input type="password" id="loginPassword" name="password"
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                        placeholder="请输入密码" required>
                </div>
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <input type="checkbox" id="rememberMe" name="rememberMe"
                            class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                        <label for="rememberMe" class="ml-2 block text-sm text-gray-700">记住我</label>
                    </div>
                    <a href="#" class="text-sm text-blue-600 hover:text-blue-800">忘记密码?</a>
                </div>
                <button type="submit"
                    class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    登录
                </button>
            </form>
        </div>
    </div>

    <!-- 侧边栏 -->
    <aside class="w-64 bg-white shadow-md">
        <div class="p-4">
            <h1 class="text-2xl font-bold text-gray-800">会员中心</h1>
            <!-- 登录按钮 -->
            <button id="showLoginModalBtn" class="login-button w-full mt-4">
                <i class="fa fa-sign-in mr-2"></i> 立即登录
            </button>
            <!-- 用户名显示 -->
            <div id="usernameDisplay" class="mt-3 text-center text-gray-600 hidden">
                <i class="fa fa-user-circle mr-1"></i>
                <span id="currentUsername"></span>
            </div>
        </div>
        <nav class="mt-4">
            <ul>
                <li>
                    <a href="index.html" class="sidebar-item">
                        <i class="fa fa-cloud-upload"></i>
                        上传文档
                    </a>
                </li>
                <!-- 新增：文档管理 菜单项 -->
                <li>
                    <a href="documents.html" class="sidebar-item">
                        <i class="fa fa-folder-open"></i> <!-- 使用文件夹打开图标，与文档管理语义匹配 -->
                        文档管理
                    </a>
                </li>
                <!-- 新增：公众号管理 菜单项 -->
                <li>
                    <a href="wechat-accounts.html" class="sidebar-item">
                        <i class="fa fa-weixin"></i>
                        公众号管理
                    </a>
                </li>
                <!-- 新增：账号管理 菜单项 -->
                <li>
                    <a href="wechat-account-management.html" class="sidebar-item active">
                        <i class="fa fa-user-circle-o"></i>
                        账号管理
                    </a>
                </li>
                <!-- 新增：抓取管理 菜单项 -->
                <li>
                    <a href="scraping.html" class="sidebar-item">
                        <i class="fa fa-scissors"></i>
                        抓取管理
                    </a>
                </li>
                <!-- 新增：数据库配置 菜单项 -->
                <li>
                    <a href="database-config.html" class="sidebar-item">
                        <i class="fa fa-database"></i>
                        数据库配置
                    </a>
                </li>
                <!-- 新增：发布管理 菜单项 -->
                <li>
                    <a href="publish-management.html" class="sidebar-item">
                        <i class="fa fa-paper-plane"></i>
                        发布管理
                    </a>
                </li>
                <!-- 退出登录 -->
                <li class="logout-item hidden">
                    <a href="#" id="logoutLink" class="sidebar-item text-gray-500 hover:text-red-500">
                        <i class="fa fa-sign-out"></i>
                        退出登录
                    </a>
                </li>
            </ul>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="flex-1 p-6">
        <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">账号管理</h2>
            <p class="text-gray-600 mb-6">管理您的公众号账号信息，包括账号详情、授权状态和账号配置。</p>

            <!-- 账号列表区域 -->
            <div class="mb-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-lg font-semibold text-gray-700">账号列表</h3>
                    <button id="addAccountBtn"
                        class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 transition-all">
                        <i class="fa fa-plus mr-2"></i>添加账号
                    </button>
                </div>

                <!-- 账号列表将通过JavaScript动态生成 -->
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <!-- 账号卡片将在这里动态生成 -->
                </div>
            </div>


        </div>
    </main>

    <!-- 登录相关脚本 -->
    <script>
        // 点击登录按钮跳转到登录页面
        document.getElementById('showLoginModalBtn')?.addEventListener('click', function () {
            window.location.href = '/login.html';
        });

        // 关闭登录弹窗
        document.getElementById('closeLoginModalBtn')?.addEventListener('click', function () {
            document.getElementById('loginModal').classList.add('hidden');
        });

        // 点击弹窗外部关闭弹窗
        document.getElementById('loginModal')?.addEventListener('click', function (e) {
            if (e.target === this) {
                this.classList.add('hidden');
            }
        });

        // 登录表单提交
        document.getElementById('loginForm')?.addEventListener('submit', function (e) {
            e.preventDefault();

            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;

            if (!username || !password) {
                alert('用户名和密码不能为空');
                return;
            }

            // 创建URL参数
            const params = new URLSearchParams();
            params.append('username', username);
            params.append('password', password);
            params.append('rememberMe', document.getElementById('rememberMe').checked ? 'on' : 'off');

            const loginBtn = this.querySelector('button[type="submit"]');
            loginBtn.disabled = true;
            loginBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 登录中...';

            // 发送登录请求
            fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: params
            })
                .then(response => response.json())
                .then(data => {
                    loginBtn.disabled = false;
                    loginBtn.innerHTML = '登录';

                    if (data.code === 0) {
                        // 登录成功，存储登录状态
                        localStorage.setItem('isLoggedIn', 'true');
                        localStorage.setItem('username', username);

                        // 关闭登录弹窗
                        document.getElementById('loginModal').classList.add('hidden');

                        // 更新登录UI
                        updateLoginUI();

                        // 显示成功提示
                        alert('登录成功！');
                    } else {
                        // 登录失败，显示错误信息
                        alert(data.message || '登录失败，请检查用户名和密码');
                    }
                })
                .catch(error => {
                    console.error('登录请求失败:', error);
                    loginBtn.disabled = false;
                    loginBtn.innerHTML = '登录';
                    alert('网络错误，请稍后再试');
                });
        });

        // 退出登录功能
        document.getElementById('logoutLink')?.addEventListener('click', function (e) {
            e.preventDefault();

            // 先调用后端logout接口
            fetch('/logout', {
                method: 'GET',
                credentials: 'same-origin'
            })
                .then(() => {
                    // 清除登录状态
                    localStorage.removeItem('isLoggedIn');
                    localStorage.removeItem('username');

                    // 更新UI显示
                    updateLoginUI();

                    // 显示退出成功提示
                    alert('退出成功！');

                    // 刷新页面以确保完全退出
                    location.reload();
                })
                .catch(error => {
                    console.error('退出登录请求失败:', error);
                    // 即使请求失败，也清除localStorage并更新UI
                    localStorage.removeItem('isLoggedIn');
                    localStorage.removeItem('username');
                    updateLoginUI();
                    alert('已清除本地登录状态！');
                });
        });

        // 更新登录UI状态
        async function updateLoginUI() {
            // 更新登录按钮显示
            const loginButton = document.getElementById('showLoginModalBtn');

            // 更新退出登录项显示
            const logoutItem = document.querySelector('.logout-item');

            // 更新用户名显示
            const usernameDisplay = document.getElementById('usernameDisplay');
            const currentUsername = document.getElementById('currentUsername');

            const loginStatus = await checkLoginStatus();

            if (loginStatus.isLoggedIn && loginStatus.username) {
                if (loginButton) {
                    loginButton.style.display = 'none';
                }
                if (logoutItem) {
                    logoutItem.classList.remove('hidden');
                }
                if (usernameDisplay && currentUsername) {
                    currentUsername.textContent = loginStatus.username;
                    usernameDisplay.classList.remove('hidden');
                }
            } else {
                if (loginButton) {
                    loginButton.style.display = 'block';
                }
                if (logoutItem) {
                    logoutItem.classList.add('hidden');
                }
                if (usernameDisplay) {
                    usernameDisplay.classList.add('hidden');
                }
            }
        }

        // 检查登录状态的函数
        function checkLoginStatus() {
            return new Promise((resolve) => {
                // 首先检查localStorage中的登录状态
                const localStorageLoggedIn = localStorage.getItem('isLoggedIn');
                const localStorageUsername = localStorage.getItem('username');

                if (localStorageLoggedIn === 'true' && localStorageUsername) {
                    // 即使localStorage中有登录状态，也需要向服务器验证
                    fetch('/check-login')
                        .then(response => response.json())
                        .then(data => {
                            if (data.code === 0 && data.isLoggedIn) {
                                // 服务器验证通过，确认登录状态
                                resolve({ isLoggedIn: true, username: data.username || localStorageUsername });
                            } else {
                                // 服务器验证失败，清除localStorage
                                localStorage.removeItem('isLoggedIn');
                                localStorage.removeItem('username');
                                resolve({ isLoggedIn: false, username: null });
                            }
                        })
                        .catch(error => {
                            console.error('验证登录状态失败:', error);
                            // 请求失败时，不应该信任localStorage，返回未登录状态
                            localStorage.removeItem('isLoggedIn');
                            localStorage.removeItem('username');
                            resolve({ isLoggedIn: false, username: null });
                        });
                } else {
                    // localStorage中没有登录状态，返回未登录
                    resolve({ isLoggedIn: false, username: null });
                }
            });
        }

        // 页面加载时检查登录状态
        document.addEventListener('DOMContentLoaded', function () {
            updateLoginUI();
        });
        // 添加账号功能通过引入外部文件实现
    </script>

    <!-- 引入添加账号弹窗 -->
    <div id="modalContainer"></div>
    <script src="add-account-modal.js"></script>
    
    <!-- 引入账号管理功能 -->
    <script src="account-management.js"></script>
</body>

</html>